import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  Select,
  message
} from 'antd'
import { observer } from 'mobx-react-lite'
import { PlusOutlined } from '@ant-design/icons'
import { Link, useSearchParams } from 'react-router-dom'
import './index.scss'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import { useStore } from '@/store'
import { useEffect, useRef, useState } from 'react'
import { http } from '@/utils'
import { history } from '@/utils/history'
// import { type } from '@testing-library/user-event/dist/type'

const { Option } = Select

const Publish = () => {
  const { channelStore } = useStore()
  const [fileList, setFileList] = useState([])
  //使用useRef暂存仓库
  const cacheImgList = useRef()
  const onUploadChange = ({ fileList }) => {
    const formatList = fileList.map(file => {
      //上传完毕 做数据处理
      if (fileList.response) {
        return { url: file.response.data.url }
      }
      return file
      // console.log(fileList)
    })
    setFileList(formatList)
    //同时把图片列表存入仓库一份
    cacheImgList.current = formatList

  }

  //切换封面选择
  const [imgCount, setImgCount] = useState(1)

  const changeType = e => {
    const count = e.target.value
    setImgCount(count)
    //通过调用
    // if (cacheImgList.current.length === 0) { return false }
    if (count === 1) {
      const img = cacheImgList.current ? cacheImgList.current[0] : []
      setFileList([img])
    } else if (count === 3) {
      setFileList(cacheImgList.current)
    }
  }
  //文章发布
  const onFinish = async (values) => {
    // const navigate = Navigate()
    //数据的二次处理，重点处理cover字段
    const { channel_id, content, title, type } = values
    console.log(values)
    const params = {
      channel_id, content, title, type,
      cover: {
        type: type,
        images: fileList.map(item => item.response.data.url)
      }
    }
    if (id) {
      await http.put(`/mp/articles/${id}?draft=false`, params)
    } else {
      await http.post('/mp/articles?draft=false', params)
    }
    //跳转列表 提示用户
    history.push('/article')
    message.success(`${id ? '更新成功' : '发布成功'}`)

  }
  //编辑功能
  const [params] = useSearchParams()
  const id = params.get('id')
  //数据回填 ID调用接口
  const form = useRef(null)
  useEffect(() => {
    const loadDetail = async () => {
      const res = await http.get(`/mp/articles/${id}`)
      //表单数据回填 实例方法
      const data = res.data
      form.current.setFieldsValue({ ...data, type: data.cover.type })
      //调用setFileList方法回填upload
      //封装
      const formatImgList = data.cover.images.map(url => {
        return {
          url
        }
      })
      setFileList(formatImgList)
      //暂存列表也存一份(暂存列表和fileList回显列表保持数据结构统一就可以)
      cacheImgList.current = formatImgList

    }
    //必须是编辑状态 才可以发送请求
    if (id) {
      loadDetail(id)
    }
  }, [id])

  return (
    <div className="publish">
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>{id ? '编辑' : '发布'}文章</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ content: '' }}
          onFinish={onFinish}
          ref={form}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入文章标题' }]}
          >
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '请选择文章频道' }]}
          >
            <Select placeholder="请选择文章频道" style={{ width: 400 }}>
              {channelStore.channelList.map(item => (
                <Option value={item.id} key={item.id}>{item.name}</Option>))}
            </Select>
          </Form.Item>

          <Form.Item label="封面">
            <Form.Item name="type">
              <Radio.Group onChange={changeType}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {imgCount > 0 && (
              <Upload
                name="image"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList
                action="http://geek.itheima.net/v1_0/upload"
                fileList={fileList}
                onChange={onUploadChange}
                //开启多选
                multiple={imgCount > 1}
                //最大上传数量
                maxCount={imgCount}
              >
                <div style={{ marginTop: 8 }}>
                  <PlusOutlined />
                </div>
              </Upload>
            )}
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '请输入文章内容' }]}
          >
            <ReactQuill
              className="publish-quill"
              theme="snow"
              placeholder="请输入文章内容"
            />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size="large" type="primary" htmlType="submit">
                {id ? '编辑' : '发布'}文章
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default observer(Publish)